from flask import Blueprint, request, jsonify, session
from models.user import User
from app import db
import requests
import uuid

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/wechat/login', methods=['POST'])
def wechat_login():
    """微信登录"""
    try:
        data = request.get_json()
        code = data.get('code')
        
        if not code:
            return jsonify({'error': '缺少授权码'}), 400
        
        # TODO: 使用微信API获取用户信息
        # 这里暂时返回模拟数据，实际需要调用微信API
        # app_id = current_app.config.get('WECHAT_APP_ID')
        # app_secret = current_app.config.get('WECHAT_APP_SECRET')
        # 
        # # 获取access_token
        # token_url = f"https://api.weixin.qq.com/sns/oauth2/access_token"
        # token_params = {
        #     'appid': app_id,
        #     'secret': app_secret,
        #     'code': code,
        #     'grant_type': 'authorization_code'
        # }
        # token_response = requests.get(token_url, params=token_params)
        # token_data = token_response.json()
        
        # 模拟微信用户信息
        unionid = f"mock_unionid_{uuid.uuid4().hex[:8]}"
        openid = f"mock_openid_{uuid.uuid4().hex[:8]}"
        nickname = data.get('nickname', '猫咪爱好者')
        avatar_url = data.get('avatar_url', '')
        
        # 查找或创建用户
        user = User.query.filter_by(unionid=unionid).first()
        if not user:
            user = User(
                unionid=unionid,
                openid=openid,
                nickname=nickname,
                avatar_url=avatar_url
            )
            db.session.add(user)
            db.session.commit()
        else:
            # 更新用户信息
            user.nickname = nickname
            user.avatar_url = avatar_url
            db.session.commit()
        
        # 设置session
        session['user_id'] = user.id
        session['unionid'] = user.unionid
        
        return jsonify({
            'message': '登录成功',
            'user': user.to_dict(),
            'token': f"mock_token_{user.id}"  # 实际项目中使用JWT
        })
        
    except Exception as e:
        return jsonify({'error': f'登录失败: {str(e)}'}), 500

@auth_bp.route('/logout', methods=['POST'])
def logout():
    """登出"""
    session.clear()
    return jsonify({'message': '登出成功'})

@auth_bp.route('/profile', methods=['GET'])
def get_profile():
    """获取用户信息"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': '未登录'}), 401
    
    user = User.query.get(user_id)
    if not user:
        return jsonify({'error': '用户不存在'}), 404
    
    # 重置每日配额
    user.reset_daily_quota()
    
    return jsonify({
        'user': user.to_dict(),
        'can_generate': user.can_generate()
    })

@auth_bp.route('/profile', methods=['PUT'])
def update_profile():
    """更新用户信息"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': '未登录'}), 401
    
    user = User.query.get(user_id)
    if not user:
        return jsonify({'error': '用户不存在'}), 404
    
    try:
        data = request.get_json()
        
        if 'nickname' in data:
            user.nickname = data['nickname']
        if 'phone' in data:
            user.phone = data['phone']
        if 'email' in data:
            user.email = data['email']
        
        db.session.commit()
        
        return jsonify({
            'message': '更新成功',
            'user': user.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新失败: {str(e)}'}), 500